package com.wwinsoft.framework.utils;

import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.wwinsoft.framework.pojo.common.MenuTree;
import com.wwinsoft.framework.pojo.common.MenuTreeNode;

/**
 * @author: Tim Chen
 * @since 1.0
 */
public class MenuUtils {

    public static Collection<MenuTree> buildMenuTree(List<? extends MenuTreeNode> treeNodeList) {
        Map<Serializable, MenuTree> menuTreeMap = new LinkedHashMap<Serializable, MenuTree>();
        for (MenuTreeNode treeNode : treeNodeList) {
            menuTreeMap.put(treeNode.getId(), new MenuTree(treeNode));
        }

        for (MenuTreeNode current : treeNodeList) {
            if (current.getParentNodeId() == null) {
                continue;
            }
            MenuTree parentMenu = menuTreeMap.get(current.getParentNodeId());
            if (parentMenu == null) {
                continue;
            }
            MenuTree currentMenuTree = menuTreeMap.get(current.getId());
            parentMenu.addChild(currentMenuTree);
            currentMenuTree.setHasParent(true);
        }

        for (Iterator<MenuTree> iterator = menuTreeMap.values().iterator(); iterator.hasNext(); ) {
            MenuTree next = iterator.next();
            if (next.isHasParent()) {
                iterator.remove();
            }
        }

        return menuTreeMap.values();
    }

    public static MenuTree buildMenuTreeWithRoot(List<? extends MenuTreeNode> authorityList, String rootName) {
        Collection<MenuTree> menuTrees = buildMenuTree(authorityList);
        MenuTree rootMenu = new MenuTree();
        rootMenu.setData(rootName);
        rootMenu.addAttr("rel", "root");
        rootMenu.addAttr("id", -1);
        rootMenu.addAttr("name", rootName);
        rootMenu.setChildren(menuTrees);
        return rootMenu;
    }

}
